package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.UserBean;
import com.project.mapper.IGradeMapper;
import com.project.mapper.IRoleMapper;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private IGradeMapper gradeMapper;

    @Override
    public UserBean findByName(String userName) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_name",userName);

        UserBean user = userMapper.selectOne(qw);
        if(user != null) {
            user.setRoleList(roleMapper.findByUser(user.getId()));
            user.setGradeList(gradeMapper.findByUser(user.getId()));
        }
        return user;
    }

    @Override
    public void add(UserBean user) {
        user.setSalt(this.getSalt());
        Md5Hash md5Hash = new Md5Hash(user.getPwd(),user.getSalt(),1024);
        user.setPwd(md5Hash.toHex());
        userMapper.insert(user);
    }

    public void update(Integer id,String newPwd){
        UserBean user = userMapper.selectById(id);
        Md5Hash md5Hash = new Md5Hash(newPwd,user.getSalt(),1024);
        user.setPwd(md5Hash.toHex());
        userMapper.updateById(user);
    }

    private String getSalt(){
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()";
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<6;i++){
            int index = (int)(Math.random()*str.length());
            sb.append(str.charAt(index));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        UserServiceImpl service = new UserServiceImpl();
        System.out.println(service.getSalt());
    }
}
